package com.mio.web.controller.product;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.durcframework.core.DefaultGridResult;
import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.UserContext;
import org.durcframework.core.controller.CrudController;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mio.web.common.MioConstants;
import com.mio.web.common.MioInfoTips;
import com.mio.web.common.MioUtil;
import com.mio.web.entity.product.Product;
import com.mio.web.entity.product.ProductSch;
import com.mio.web.entity.recommend.Recommand;
import com.mio.web.entity.producttype.Producttype;
import com.mio.web.entity.producttype.ProducttypeSch;
import com.mio.web.entity.sys.SysUpload;
import com.mio.web.service.product.ProductService;
import com.mio.web.service.producttype.ProducttypeService;
import com.mio.web.service.sys.SysUploadService;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class ProductController extends CrudController<Product, ProductService> {
	@Autowired
	SysUploadService sysUploadService;
	@Autowired
	private ProducttypeService productTypeService;
	
	@RequestMapping("/product.do")
	public ModelAndView getProductJsp(HttpServletRequest request){
		ModelAndView model = new ModelAndView("/product.jsp");
		//获取登录用户
		model.addObject("loginUser",UserContext.getInstance().getUser());
		//获取横幅
		SysUpload banner = sysUploadService.getFirstSysUploadByFuncId("productBanner");
		model.addObject("banner", banner);
		//获取所有的产品副类
		List<Producttype> assistantType = productTypeService.getAssistantType(new ProducttypeSch());
		ExpressionQuery query = new ExpressionQuery();
		query.add(new ValueExpression("parentId",0));
		query.addSort("sortId");
		query.setIsQueryAll(true);
		//获取所有产品主类
		List<Producttype> mainType = productTypeService.find(query);
		//把副类塞到主类中
		for(int i = 0; i<mainType.size(); i++){
			ArrayList<Producttype> types = new ArrayList<Producttype>();
			for(int j = 0 ;j<assistantType.size(); j++){
				if(assistantType.get(j).getParentId().equals(mainType.get(i).getId())){
					types.add(assistantType.get(j));
					assistantType.remove(j);
					j--;
				}
			}
			mainType.get(i).setNodes(types);
		}
		//获取所选的副类类别的产品
		String productTypeId = request.getParameter("productType");
		String mainTypeId = request.getParameter("mainTypeId");
		String pages = request.getParameter("pageStart");
		String pageTotal = request.getParameter("pageCount");
		
		//如果选中副类
		if(productTypeId != null){
			//设置副类的id
			model.addObject("productTypeId",Integer.parseInt(productTypeId));
			//设置主类的id
			if(mainTypeId != null){
				model.addObject("mainTypeId",Integer.parseInt(mainTypeId));
			}else{
				//获取副类的parentId也就是主类的Id。
				model.addObject("mainTypeId",productTypeService.get(Integer.parseInt(productTypeId)).getParentId());
			}
			query = new ExpressionQuery();
			query.add(new ValueExpression("productTypeId",Integer.parseInt(productTypeId)));
			query.addSort("sortId");
			query.setPageSize(20);
			int pageNum  = 1;
			if(pages != null){
				pageNum = Integer.parseInt(pages);
				query.setStart((pageNum-1)*20);
			}else{
				query.setStart(0);
			}
			//设置起始页数
			model.addObject("pageStart", pageNum);
			List<Product> products = this.getService().find(query);
			//设置查询的产品列表
			model.addObject("products", products);
			
			int pageCount = 0;
			//判断是否有总页数的值
			if(pageTotal != null){
				int total = Integer.parseInt(pageTotal);
				pageCount = total;
			}else{
				//查询该类别的所有的数据
				query = new ExpressionQuery();
				query.add(new ValueExpression("productTypeId",Integer.parseInt(productTypeId)));
				pageCount = this.getService().findTotalCount(query)/20 + 1;
			}
			//设置总页数
			model.addObject("pageCount",pageCount);
		//如果未选中副类	
		}else{
			//设置副类的id
			model.addObject("productTypeId",mainType.get(0).getNodes().get(0).getId());
			//设置主类的id
			model.addObject("mainTypeId",mainType.get(0).getId());
			query = new ExpressionQuery();
			query.add(new ValueExpression("productTypeId",mainType.get(0).getNodes().get(0).getId()));
			query.addSort("sortId");
			query.setPageSize(20);
			query.setStart(0);
			int pageNum  = 1;
			//设置起始页数
			model.addObject("pageStart", pageNum);
			List<Product> products = this.getService().find(query);
			//设置查询的产品列表
			model.addObject("products", products);
			
			int pageCount = 0;
			//查询该类别的所有的数据
			query = new ExpressionQuery();
			query.add(new ValueExpression("productTypeId",mainType.get(0).getNodes().get(0).getId()));
			pageCount = this.getService().findTotalCount(query)/20 + 1;
			//设置总页数
			model.addObject("pageCount",pageCount);
		}
		model.addObject("productTypes", mainType);
		return model;
		
	}
	
	@RequestMapping("/productDetail.do")
	public ModelAndView getProductDetail(HttpServletRequest request){
		ModelAndView model = new ModelAndView("/productDetail.jsp");
		//获取登录用户
		model.addObject("loginUser",UserContext.getInstance().getUser());
		//获取横幅
		SysUpload banner = sysUploadService.getFirstSysUploadByFuncId("productBanner");
		model.addObject("banner", banner);
		//获取所有的产品副类
		List<Producttype> assistantTypes = productTypeService.getAssistantType(new ProducttypeSch());
		ExpressionQuery query = new ExpressionQuery();
		query.add(new ValueExpression("parentId",0));
		query.addSort("sortId");
		query.setIsQueryAll(true);
		//获取所有产品主类
		List<Producttype> mainType = productTypeService.find(query);
		//把副类塞到主类中
		for(int i = 0; i<mainType.size(); i++){
			ArrayList<Producttype> types = new ArrayList<Producttype>();
			for(int j = 0 ;j<assistantTypes.size(); j++){
				if(assistantTypes.get(j).getParentId().equals(mainType.get(i).getId())){
					types.add(assistantTypes.get(j));
					assistantTypes.remove(j);
					j--;
				}
			}
			mainType.get(i).setNodes(types);
		}
		//获取所选的副类类别的产品
		String productTypeId = request.getParameter("productType");
		String mainTypeId = request.getParameter("mainTypeId");
		
		//获取产品Id
		String productId = request.getParameter("productId");
		
		//获取产品
		Product product = this.getService().get(productId);
		String[] picIds = product.getPicId().split(",");
		ArrayList<SysUpload> sysFile = new ArrayList<SysUpload>();
		for(int i = 0; i<picIds.length; i++){
			SysUpload s = sysUploadService.get(Integer.parseInt(picIds[i]));
			//s.setFileFullPath(s.getFileFullPath().substring(s.getFileFullPath().lastIndexOf("/")+1));
			sysFile.add(s);
		}
		//副类Id
		int typeId = 0;
		if(productTypeId == null){
			typeId = product.getProductTypeId();
			
		}else{
			typeId = Integer.parseInt(productTypeId);
		}
		//设置副类的Id
		model.addObject("productTypeId",typeId);
		//主类Id
		int mainId = 0;
		if(mainTypeId == null){
			Producttype assistantType = productTypeService.get(typeId);
			mainId = assistantType.getParentId();
		}else{
			mainId = Integer.parseInt(mainTypeId);
		}
		
		model.addObject("mainTypeId",mainId);
		product.setSysFile(sysFile);
		model.addObject("product", product);
		model.addObject("productTypes", mainType);
		return model;
	}
	
	// ������¼
	@RequestMapping("/addProduct.do")
	public @ResponseBody Map<String, Object> addProduct(Product product, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/product/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				List<SysUpload> sysUploads = new ArrayList<SysUpload>();
				String picId = "";
				int count = 0;
				// 产品图
				String productImg = "";
				while (iter.hasNext()) {
					System.out.println(iter.hasNext());
					count++;
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String fileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (!fileName.trim().equals("")) {
							System.out.println(fileName);
							// 定义上传路径
							File targetFile = MioUtil.getUploadFile(request, "product", fileName,response);
							file.transferTo(targetFile);

							SysUpload sysUpload = new SysUpload();
							sysUpload.setFileSize((int) file.getSize());
							sysUpload.setFileFullPath(relPath + fileName);
							sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
							sysUpload.setFuncId("product");
							sysUpload = sysUploadService.save(sysUpload);
							// 拼接上传文件的id
							if (count == 1) {
								productImg = relPath + fileName;
							} else {
								picId = picId + sysUpload.getId() + ",";
							}
							sysUploads.add(sysUpload);

						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}

				// 保存产品信息
				product.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				product.setmImgUrl(productImg);
				product.setUploadList(sysUploads);
				if (!StringUtils.isEmpty(picId)) {
					picId = picId.substring(0, picId.length() - 1);
					product.setPicId(picId);
				}
				product = this.getService().save(product);

			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		resultMap.put("success", true);
		resultMap.put("info", product);

		return resultMap;
		// return this.save(entity);
	}

	// ɾ����¼
	@RequestMapping("/delProduct.do")
	public @ResponseBody MessageResult delProduct(Product entity) {
		return this.delete(entity);
	}

	// �޸ļ�¼
	@RequestMapping("/updateProduct.do")
	public @ResponseBody MessageResult updateProduct(Product entity,HttpServletRequest request,HttpServletResponse response) 
			throws IllegalStateException, IOException  {
		Product old = this.get(entity.getId());
		boolean change[] = new boolean[6];
		int flag = 1;
		int surplus = 0;
		int change0 = Integer.parseInt(request.getParameter("change0"));
		if(change0>0){
			change[0] = true;
		}
		int change1 = Integer.parseInt(request.getParameter("change1"));
		//表示修改
		if(change1>0){
			change[flag] = true;
			surplus++;
		//表示清除
		}else if(change1 == 0){
			clearFile(old, 1);
			flag--;
		}
		flag ++;
		int change2 = Integer.parseInt(request.getParameter("change2"));
		if(change2>0){
			change[flag] = true;
			surplus++;
		}else if(change2 == 0){
			clearFile(old, 2);
			flag--;
		}
		flag ++;
		int change3 = Integer.parseInt(request.getParameter("change3"));
		if(change3>0){
			change[flag] = true;
			surplus++;
		}else if(change3 == 0){
			clearFile(old, 3);
			flag --;
		}
		flag ++;
		int change4 = Integer.parseInt(request.getParameter("change4"));
		if(change4>0){
			change[flag] = true;
			surplus++;
		}else if(change4 == 0){
			clearFile(old, 4);
			flag --;
		}
		flag ++;
		int change5 = Integer.parseInt(request.getParameter("change5"));
		if(change5>0){
			change[flag] = true;
			surplus++;
		}else if(change5 == 0){
			clearFile(old, 5);
			flag --;
		}
		flag ++;
		//说明有清除操作但是没有修改操作
		if(flag <6 && surplus == 0){
			entity.setPicId(old.getPicId());
		}
		
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/product/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				String picId = "";
				int count = 0;
				// 产品图
				String productImg = "";
				while (iter.hasNext()) {
					for(int i = count; i<6; i++){
						count++;
						//如果对应位置的图片信息发生了变化
						if(change[i]){
							System.out.println(i+"  "+iter.hasNext());
							// 记录上传过程起始时的时间，用来计算上传时间
							int pre = (int) System.currentTimeMillis();
							// 取得上传文件
							MultipartFile file = multiRequest.getFile(iter.next());
							if (file != null) {
								// 取得当前上传文件的文件名称
								String fileName = file.getOriginalFilename();
								// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
								if (!fileName.trim().equals("")) {
									System.out.println(fileName);
									// 定义上传路径
									File targetFile = MioUtil.getUploadFile(request, "product", fileName,response);
									file.transferTo(targetFile);
		
									SysUpload sysUpload = new SysUpload();
									sysUpload.setFileSize((int) file.getSize());
									sysUpload.setFileFullPath(relPath + fileName);
									sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
									sysUpload.setFuncId("product");
									sysUpload = sysUploadService.save(sysUpload);
									// 拼接上传文件的id
									if (i == 0) {
										productImg = relPath + fileName;
									} else {
										String picIds[] = old.getPicId().split(",");
										for(int j = 0; j<picIds.length+surplus; j++){
											if(j+2 == count){
												picId = picId + sysUpload.getId()+",";
											}else{
												if(j<picIds.length){
													picId = picId + picIds[j]+",";
												}
												
											}
										}
									}
		
								}
								
							}
						}
		
						// 保存产品信息
						if(!productImg.equals("")){
							entity.setmImgUrl(productImg);
							productImg ="";
						}
						if (!StringUtils.isEmpty(picId)) {
							picId = picId.substring(0, picId.length() - 1);
							old.setPicId(picId);
							entity.setPicId(picId);
							picId = "";
						}
					}
				}


			}
		} catch (Exception e) {
			e.printStackTrace();

		}

		return this.update(entity);
	}

	// ������ѯ��ҳ����
	@RequestMapping("/listProduct.do")
	public @ResponseBody GridResult listProduct(ProductSch searchEntitySch) {
		DefaultGridResult result = (DefaultGridResult)this.query(searchEntitySch);
		List<Product> products = (List<Product>)result.getRows();
		return result;
	}

	// ������ѯ���������м�¼
	@RequestMapping("/listAllProduct.do")
	public @ResponseBody Object listAllProduct(ProductSch searchEntitySch) {
		return this.queryAll(searchEntitySch);
	}

	// ��ȡ��ϸ��Ϣ
	@RequestMapping("/getProductById.do")
	public @ResponseBody Product getProductById(Product entity) {
		return this.getService().get(entity.getId());
	}

	/**
	 * 获取十大热销产品
	 * 
	 * @param searchEntitySch
	 * @return
	 */
	@RequestMapping("/listHotProduct.do")
	public @ResponseBody Map<String, Object> listHotProduct(ProductSch searchEntitySch) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<Product> list = this.getService().listIndexProduct();
			resultMap.put("success", true);
			resultMap.put("info", list);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		return resultMap;

	}

	/**
	 * 添加产品，并且保存产品图片
	 * 
	 * @param searchEntitySch
	 * @return
	 */
	@RequestMapping("/saveProductInfo.do")
	public @ResponseBody Map<String, Object> saveProductInfo(HttpServletRequest request, MultipartFile file,
			Product product) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String path = request.getSession().getServletContext().getRealPath("upload/product");
			String relPath = "/upload/product/";
			String fileName = file.getOriginalFilename();
			// 大图
			File dir = MioUtil.createDir(path);
			File targetFile = MioUtil.createFile(dir, fileName);
			// 小图
			String fileNameSmall = "s_" + file.getOriginalFilename();
			File targetFileSmall = MioUtil.createFile(dir, fileNameSmall);

			if (targetFile != null) {
				FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
				// 同时保存小图到相应的文件中
				Thumbnails.of(targetFile).size(MioConstants.THUMB_SMALL_WIDTH, MioConstants.THUMB_SMALL_HEIGHT)
						.toFile(targetFileSmall);
				product.setMImgUrl(relPath + fileName);
				product.setSImgUrl(relPath + fileNameSmall);
				product = this.getService().save(product);
				resultMap.put("success", true);
				resultMap.put("info", product);
			} else {
				resultMap.put("success", false);
				resultMap.put("info", MioInfoTips.CREATE_FILE_FAIL);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		return resultMap;

	}

	@RequestMapping("saveMultipartProductInfo.do")
	@ResponseBody
	public Map<String, Object> saveMuliProductInfo(Product product, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/product/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				List<SysUpload> sysUploads = new ArrayList<SysUpload>();
				String picId = "";
				int count = 0;
				// 产品图
				String productImg = "";
				while (iter.hasNext()) {
					count++;
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String fileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (fileName.trim() != "") {
							System.out.println(fileName);
							// 重命名上传后的文件名
							// 定义上传路径
							File targetFile = MioUtil.getUploadFile(request, "product", fileName,response);
							file.transferTo(targetFile);
							if (count == 1) {
								productImg = relPath + fileName;
							} else {
								SysUpload sysUpload = new SysUpload();
								sysUpload.setFileSize((int) file.getSize());
								sysUpload.setFileFullPath(relPath + fileName);
								sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
								sysUpload.setFuncId("product");
								sysUpload = sysUploadService.save(sysUpload);
								// 拼接上传文件的id
								picId = picId + sysUpload.getId() + ",";
								sysUploads.add(sysUpload);
							}

						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}

				// 保存产品信息
				product.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				product.setmImgUrl(productImg);
				product.setUploadList(sysUploads);
				if (!StringUtils.isEmpty(picId)) {
					picId = picId.substring(0, picId.length() - 1);
					product.setPicId(picId);
				}
				product = this.getService().save(product);

			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		resultMap.put("success", true);
		resultMap.put("info", product);

		return resultMap;
	}

	/**
	 * 前往产品详细信息页面
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping("/forwardProductDetail.do")
	public ModelAndView forwardRecommandDetail(Product entity) {
		ModelAndView modelAndView = new ModelAndView("manager/productDetail.jsp");
		Product product = this.getService().get(entity.getId());
		if (product != null) {
			String picId = product.getPicId();
			if(!StringUtils.isEmpty(picId)){
				List<SysUpload> uploads = new ArrayList<SysUpload>();
				String[] picArray = picId.split(",");
				for(String id : picArray){
					SysUpload sysUpload = sysUploadService.get(Integer.parseInt(id));
					uploads.add(sysUpload);
				}
				product.setUploadList(uploads);
			}
		}
		modelAndView.addObject("product", product);
		return modelAndView;
	}
	
	/**
	 * 清除文件
	 * @param product
	 * @param index
	 */
	public void clearFile(Product product,int index){
		String picId[] = product.getPicId().split(",");
		String picIds = "";
		for(int i = 0; i<picId.length; i++){
			if(i+1 == index){
				sysUploadService.del(sysUploadService.get(picId[i]));
			}else{
				picIds = picId[i]+",";
			}
		}
		picIds = picIds.substring(0,picIds.length()-1);
		product.setPicId(picIds);	
	}

}